package xju.rjxy.shop.web.controller;

import com.alibaba.fastjson.JSON;
import xju.rjxy.shop.common.framework.simplemvc.RequestMapping;
import xju.rjxy.shop.common.utils.JSONUtil;
import xju.rjxy.shop.common.utils.Result;
import xju.rjxy.shop.model.domain.User;
import xju.rjxy.shop.model.dto.LoginDTO;
import xju.rjxy.shop.model.dto.RegisterDTO;
import xju.rjxy.shop.model.dto.UserUpdateDTO;
import xju.rjxy.shop.model.vo.UserVO;
import xju.rjxy.shop.service.IUserService;
import xju.rjxy.shop.service.impl.UserServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

/**
 * 用户控制层
 */
@RequestMapping("/api/user")
public class UserController {
    private final IUserService userService = new UserServiceImpl();

    @RequestMapping("/list.do")
    public void getUserList(HttpServletRequest request, HttpServletResponse response) {
        // TODO 条件查询列表
        List<UserVO> userList = userService.getUserList();
        JSONUtil.printByJSON(response, Result.success(userList));
    }
    
    @RequestMapping("/login.do")
    public void login(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 添加调试信息
            System.out.println("=== 登录请求调试信息 ===");
            System.out.println("请求方法: " + request.getMethod());
            System.out.println("Content-Type: " + request.getContentType());
            System.out.println("请求参数username: " + request.getParameter("username"));
            System.out.println("请求参数password: " + request.getParameter("password"));
            
            LoginDTO loginDTO = new LoginDTO();
            
            // 尝试从请求参数中读取（支持表单提交）
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            
            if (username != null && password != null) {
                // 表单参数方式
                System.out.println("使用表单参数方式");
                loginDTO.setUsername(username);
                loginDTO.setPassword(password);
            } else {
                // JSON请求体方式
                System.out.println("使用JSON请求体方式");
                loginDTO = readRequestBody(request, LoginDTO.class);
            }
            
            System.out.println("最终loginDTO: " + loginDTO.getUsername() + ", " + loginDTO.getPassword());
            
            // 执行登录
            User user = userService.login(loginDTO);
            
            // 返回成功结果，包含用户信息（不包含密码）
            user.setPassword(null);
            System.out.println("登录成功");
            JSONUtil.printByJSON(response, Result.success(user, "登录成功"));
            
        } catch (Exception e) {
            System.out.println("登录异常: " + e.getMessage());
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/register.do")
    public void register(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 添加调试信息
            System.out.println("=== 注册请求调试信息 ===");
            System.out.println("请求方法: " + request.getMethod());
            System.out.println("Content-Type: " + request.getContentType());
            System.out.println("请求参数phoneNumber: " + request.getParameter("phoneNumber"));
            System.out.println("请求参数username: " + request.getParameter("username"));
            System.out.println("请求参数password: " + request.getParameter("password"));
            
            RegisterDTO registerDTO = new RegisterDTO();
            
            // 尝试从请求参数中读取（支持表单提交）
            String phoneNumber = request.getParameter("phoneNumber");
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            
            if (phoneNumber != null && username != null && password != null) {
                // 表单参数方式
                System.out.println("使用表单参数方式");
                registerDTO.setPhoneNumber(phoneNumber);
                registerDTO.setUsername(username);
                registerDTO.setPassword(password);
            } else {
                // JSON请求体方式
                System.out.println("使用JSON请求体方式");
                registerDTO = readRequestBody(request, RegisterDTO.class);
            }
            
            System.out.println("最终registerDTO: phoneNumber=" + registerDTO.getPhoneNumber() + 
                             ", username=" + registerDTO.getUsername() + 
                             ", password=" + (registerDTO.getPassword() != null ? "***" : "null"));
            
            // 执行注册
            User user = userService.register(registerDTO);
            
            // 返回成功结果，包含用户信息（不包含密码）
            user.setPassword(null);
            System.out.println("注册成功，用户ID: " + user.getId());
            JSONUtil.printByJSON(response, Result.success(user, "注册成功"));
            
        } catch (Exception e) {
            System.out.println("注册异常: " + e.getMessage());
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/info.do")
    public void getUserInfo(HttpServletRequest request, HttpServletResponse response) {
        try {
            String userIdStr = request.getParameter("userId");
            if (userIdStr == null || userIdStr.trim().isEmpty()) {
                JSONUtil.printByJSON(response, Result.fail("用户ID不能为空"));
                return;
            }
            
            Integer userId = Integer.parseInt(userIdStr);
            User user = userService.getUserById(userId);
            
            if (user == null) {
                JSONUtil.printByJSON(response, Result.fail("用户不存在"));
                return;
            }
            
            // 补全字段
            if (user.getAccountBalance() == null) user.setAccountBalance(0.0);
            if (user.getAccountPoints() == null) user.setAccountPoints(0);
            if (user.getCreateTime() == null) user.setCreateTime(java.time.LocalDateTime.now());
            if (user.getPhoneNumber() == null) user.setPhoneNumber("");
            if (user.getGender() == null) user.setGender("");
            if (user.getAvatar() == null) user.setAvatar("");
            if (user.getEmail() == null) user.setEmail("");

            user.setPassword(null); // 不返回密码

            // 确保响应头为utf-8
            response.setContentType("application/json; charset=utf-8");
            JSONUtil.printByJSON(response, Result.success(user));
            
        } catch (NumberFormatException e) {
            response.setContentType("application/json; charset=utf-8");
            JSONUtil.printByJSON(response, Result.fail("用户ID格式错误"));
        } catch (Exception e) {
            response.setContentType("application/json; charset=utf-8");
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/update.do")
    public void updateUserInfo(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 读取请求体
            User user = readRequestBody(request, User.class);
            
            // 执行更新
            boolean success = userService.updateUserInfo(user);
            
            if (success) {
                JSONUtil.printByJSON(response, Result.success("更新成功"));
            } else {
                JSONUtil.printByJSON(response, Result.fail("更新失败"));
            }
            
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    /**
     * 重置密码
     */
    @RequestMapping("/resetPassword.do")
    public void resetPassword(HttpServletRequest request, HttpServletResponse response) {
        try {
            String phoneNumber = request.getParameter("phoneNumber");
            String username = request.getParameter("username");
            String newPassword = request.getParameter("newPassword");
            // 如果参数为空，尝试从JSON请求体读取
            if ((phoneNumber == null || username == null || newPassword == null)
                || (phoneNumber.isEmpty() || username.isEmpty() || newPassword.isEmpty())) {
                // 读取JSON请求体
                StringBuilder sb = new StringBuilder();
                BufferedReader reader = request.getReader();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSON.parseObject(sb.toString());
                phoneNumber = json.getString("phoneNumber");
                username = json.getString("username");
                newPassword = json.getString("newPassword");
            }
            boolean success = userService.resetPassword(phoneNumber, username, newPassword);
            if (success) {
                JSONUtil.printByJSON(response, Result.success("密码重置成功"));
            } else {
                JSONUtil.printByJSON(response, Result.fail("重置失败，手机号或用户名不正确"));
            }
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    /**
     * 更新用户信息
     */
    @RequestMapping("/updateInfo.do")
    public void updateUserInfo1(HttpServletRequest request, HttpServletResponse response) {
        try {
            System.out.println("=== 用户信息更新请求调试信息 ===");
            System.out.println("请求方法: " + request.getMethod());
            System.out.println("Content-Type: " + request.getContentType());
            System.out.println("请求URL: " + request.getRequestURL());
            
            // 打印请求参数
            System.out.println("--- 请求参数 ---");
            java.util.Enumeration<String> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = paramNames.nextElement();
                String paramValue = request.getParameter(paramName);
                System.out.println("参数名: " + paramName + ", 参数值: " + paramValue);
            }
            
            // 读取请求体
            System.out.println("--- 读取请求体 ---");
            StringBuilder requestBody = new StringBuilder();
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                requestBody.append(line);
            }
            String bodyContent = requestBody.toString();
            System.out.println("请求体内容: " + bodyContent);
            
            // 解析JSON
            System.out.println("--- JSON解析 ---");
            UserUpdateDTO userUpdateDTO = null;
            if (bodyContent != null && !bodyContent.trim().isEmpty()) {
                try {
                    userUpdateDTO = com.alibaba.fastjson.JSON.parseObject(bodyContent, UserUpdateDTO.class);
                    System.out.println("JSON解析成功");
                    System.out.println("解析后的DTO对象: " + userUpdateDTO);
                    if (userUpdateDTO != null) {
                        System.out.println("用户ID: " + userUpdateDTO.getId());
                        System.out.println("用户名: " + userUpdateDTO.getUsername());
                        System.out.println("邮箱: " + userUpdateDTO.getEmail());
                        System.out.println("性别: " + userUpdateDTO.getGender());
                        System.out.println("头像: " + userUpdateDTO.getAvatar());
                    }
                } catch (Exception e) {
                    System.out.println("JSON解析失败: " + e.getMessage());
                    e.printStackTrace();
                    JSONUtil.printByJSON(response, Result.fail("JSON格式错误: " + e.getMessage()));
                    return;
                }
            } else {
                System.out.println("请求体为空，尝试从参数获取");
                // 尝试从请求参数构建DTO
                userUpdateDTO = new UserUpdateDTO();
                String idStr = request.getParameter("id");
                if (idStr != null && !idStr.trim().isEmpty()) {
                    try {
                        userUpdateDTO.setId(Integer.parseInt(idStr));
                        System.out.println("从参数获取用户ID: " + userUpdateDTO.getId());
                    } catch (NumberFormatException e) {
                        System.out.println("用户ID格式错误: " + idStr);
                        JSONUtil.printByJSON(response, Result.fail("用户ID格式错误"));
                        return;
                    }
                }
                userUpdateDTO.setUsername(request.getParameter("username"));
                userUpdateDTO.setEmail(request.getParameter("email"));
                userUpdateDTO.setGender(request.getParameter("gender"));
                userUpdateDTO.setAvatar(request.getParameter("avatar"));
                System.out.println("从参数构建的DTO: " + userUpdateDTO);
            }
            
            // 验证DTO
            System.out.println("--- 验证DTO ---");
            if (userUpdateDTO == null) {
                System.out.println("DTO对象为null");
                JSONUtil.printByJSON(response, Result.fail("请求数据为空"));
                return;
            }
            
            if (userUpdateDTO.getId() == null) {
                System.out.println("用户ID为null");
                JSONUtil.printByJSON(response, Result.fail("用户ID不能为空"));
                return;
            }
            
            System.out.println("DTO验证通过，用户ID: " + userUpdateDTO.getId());
            
            // 调用服务
            System.out.println("--- 调用服务 ---");
            boolean success = userService.updateUserInfoByDTO(userUpdateDTO);
            System.out.println("服务调用结果: " + success);
            
            if (success) {
                System.out.println("用户信息更新成功");
                JSONUtil.printByJSON(response, Result.success("用户信息更新成功"));
            } else {
                System.out.println("用户信息更新失败");
                JSONUtil.printByJSON(response, Result.fail("用户信息更新失败"));
            }
            
        } catch (Exception e) {
            System.out.println("=== 异常信息 ===");
            System.out.println("异常类型: " + e.getClass().getName());
            System.out.println("异常消息: " + e.getMessage());
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail("更新失败: " + e.getMessage()));
        }
    }
    
    /**
     * 上传头像
     */
    @RequestMapping("/uploadAvatar.do")
    public void uploadAvatar(HttpServletRequest request, HttpServletResponse response) {
        try {
            String userIdStr = request.getParameter("userId");
            String avatarUrl = request.getParameter("avatarUrl");
            
            if (userIdStr == null || avatarUrl == null) {
                JSONUtil.printByJSON(response, Result.fail("用户ID和头像URL不能为空"));
                return;
            }
            
            Integer userId = Integer.parseInt(userIdStr);
            boolean success = userService.uploadAvatar(userId, avatarUrl);
            if (success) {
                JSONUtil.printByJSON(response, Result.success("头像上传成功"));
            } else {
                JSONUtil.printByJSON(response, Result.fail("头像上传失败"));
            }
        } catch (NumberFormatException e) {
            JSONUtil.printByJSON(response, Result.fail("用户ID格式错误"));
        } catch (Exception e) {
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    /**
     * 充值余额
     */
    @RequestMapping("/recharge.do")
    public void rechargeBalance(HttpServletRequest request, HttpServletResponse response) {
        try {
            System.out.println("=== 充值请求调试信息 ===");
            System.out.println("请求方法: " + request.getMethod());
            System.out.println("Content-Type: " + request.getContentType());
            System.out.println("请求参数userId: " + request.getParameter("userId"));
            System.out.println("请求参数amount: " + request.getParameter("amount"));

            String userIdStr = request.getParameter("userId");
            String amountStr = request.getParameter("amount");

            if (userIdStr == null || userIdStr.trim().isEmpty() ||
                amountStr == null || amountStr.trim().isEmpty()) {
                System.out.println("参数校验未通过：userId或amount为空");
                JSONUtil.printByJSON(response, Result.fail("用户ID和充值金额不能为空"));
                return;
            }

            Integer userId = null;
            Double amount = null;
            try {
                userId = Integer.parseInt(userIdStr.trim());
                amount = Double.parseDouble(amountStr.trim());
            } catch (NumberFormatException e) {
                System.out.println("参数格式错误：userId=" + userIdStr + ", amount=" + amountStr);
                JSONUtil.printByJSON(response, Result.fail("参数格式错误"));
                return;
            }

            System.out.println("最终userId: " + userId + ", amount: " + amount);

            boolean success = userService.rechargeBalance(userId, amount);
            System.out.println("充值业务处理结果: " + success);

            if (success) {
                JSONUtil.printByJSON(response, Result.success("充值成功"));
            } else {
                JSONUtil.printByJSON(response, Result.fail("充值失败"));
            }
        } catch (Exception e) {
            System.out.println("充值异常: " + e.getMessage());
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    /**
     * 读取请求体并转换为指定类型
     */
    private <T> T readRequestBody(HttpServletRequest request, Class<T> clazz) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        return JSON.parseObject(sb.toString(), clazz);
    }
}